package com.ruoyi.pollution.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pollution.domain.BusPsCodOutputpollutant;
import com.ruoyi.pollution.domain.BusPsCodPollutant;
import com.ruoyi.pollution.domain.PollutionAnalyseVo;
import com.ruoyi.pollution.mapper.PollutionAnalyseMapper;
import com.ruoyi.pollution.service.PollutionAnalyseService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PollutionAnalyseServiceImpl implements PollutionAnalyseService {

    @Autowired
    private PollutionAnalyseMapper pollutionAnalyseMapper;

    @Override
    public List<Map<String, Object>> dataSourcePolluteTree(PollutionAnalyseVo vo) {

        if (StringUtils.isEmpty(vo.getType())) {
            vo.setType("county");
        }

        List<Map<String, Object>> retList = pollutionAnalyseMapper.dataSourcePolluteTree(vo);

        List<Map<String, Object>> treeList = new ArrayList<>();
        if ("county".equals(vo.getType())) {
            retList.forEach(map -> {
                Map<String, Object> outputMap = new HashMap<>();
                outputMap.put("name", map.get("outPortName"));
                outputMap.put("id", map.get("outPortCode"));
                outputMap.put("status", map.get("onlineStatus"));
                if (map.get("CountyCode") != null) {
                    boolean countyFlag = false;
                    for (Map<String, Object> treeMap : treeList) {
                        if (map.get("CountyCode").equals(treeMap.get("id"))) {
                            List<Map<String, Object>> polluteList = (List<Map<String, Object>>) treeMap.get("children");
                            boolean polluteFlag = false;
                            for (Map<String, Object> polluteMap : polluteList) {
                                if (map.get("id").equals(polluteMap.get("id"))) {
                                    polluteFlag = true;
                                }
                            }
                            if (!polluteFlag) {
                                Map<String, Object> polluteMap = new HashMap<>();
                                polluteMap.put("name", map.get("polluteName"));
                                polluteMap.put("id", map.get("id"));
                                polluteMap.put("dataid", map.get("dataid"));
                                polluteMap.put("isBehavior", "0");
                                if (ObjectUtils.isNotEmpty(map.get("behaviorId"))) {
                                    polluteMap.put("isBehavior", "1");
                                }
                                polluteList.add(polluteMap);
                            }
                            countyFlag = true;
                        }
//
                    }
                    if (!countyFlag) {
                        Map<String, Object> polluteMap = new HashMap<>();
                        polluteMap.put("name", map.get("polluteName"));
                        polluteMap.put("id", map.get("id"));
                        polluteMap.put("dataid", map.get("dataid"));
                        List<Map<String, Object>> polluteList = new ArrayList<>();
                        polluteList.add(polluteMap);
                        Map<String, Object> parentMap = new HashMap<>();
                        parentMap.put("name", map.get("County"));
                        parentMap.put("id", map.get("CountyCode"));
                        parentMap.put("children", polluteList);
                        treeList.add(parentMap);
                    }
                }
            });
        } else if ("river".equals(vo.getType())) {
            retList.forEach(map -> {
                if (map.get("RiverID") != null) {
                    boolean countyFlag = false;
                    for (Map<String, Object> treeMap : treeList) {
                        if (map.get("RiverID").equals(treeMap.get("id"))) {
                            List<Map<String, Object>> polluteList = (List<Map<String, Object>>) treeMap.get("children");
                            boolean polluteFlag = false;
                            for (Map<String, Object> polluteMap : polluteList) {
                                if (map.get("id").equals(polluteMap.get("id"))) {
                                    polluteFlag = true;
                                }
                            }
                            if (!polluteFlag) {
                                Map<String, Object> polluteMap = new HashMap<>();
                                polluteMap.put("name", map.get("polluteName"));
                                polluteMap.put("id", map.get("id"));
                                polluteMap.put("isBehavior", "0");
                                polluteMap.put("dataid", map.get("dataid"));
                                if (ObjectUtils.isNotEmpty(map.get("behaviorId"))) {
                                    polluteMap.put("isBehavior", "1");
                                }
                                polluteList.add(polluteMap);
                            }
                            countyFlag = true;
                        }
                    }
                    if (!countyFlag) {
                        Map<String, Object> polluteMap = new HashMap<>();
                        polluteMap.put("name", map.get("polluteName"));
                        polluteMap.put("id", map.get("id"));
                        polluteMap.put("dataid", map.get("dataid"));
                        polluteMap.put("isBehavior", "0");
                        if (ObjectUtils.isNotEmpty(map.get("behaviorId"))) {
                            polluteMap.put("isBehavior", "1");
                        }
                        List<Map<String, Object>> polluteList = new ArrayList<>();
                        polluteList.add(polluteMap);
                        Map<String, Object> parentMap = new HashMap<>();
                        parentMap.put("name", map.get("RiverName"));
                        parentMap.put("id", map.get("RiverID"));
                        parentMap.put("children", polluteList);
                        treeList.add(parentMap);
                    }
                }
            });
        }

        return treeList;
    }

    @Override
    public Map<String, Object> dataAnalysis(PollutionAnalyseVo vo) {
        Map<String, Object> resMap = new HashMap<>();

        //获取企业监测情况
        Map<String, Object> monitorStatus = pollutionAnalyseMapper.getDataSourceMonitorStatus(vo.getId());
        if (MapUtils.isEmpty(monitorStatus)) {
            return resMap;
        }
        String IsAutomaticMonitoringEnt = monitorStatus.get("IsAutomaticMonitoringEnt").toString();
        String IsSuperviseMonitoringEnt = monitorStatus.get("IsSuperviseMonitoringEnt").toString();
        List<Map<String, Object>> automaticList = new ArrayList<>();
        List<Map<String, Object>> superviseList = new ArrayList<>();
        List<Map<String, Object>> monitorList = new ArrayList<>();
        Set<String> strList = new HashSet<>();
        Set<String> pollutantList = new HashSet<>();
        List<Map<String, Object>> dateList = new ArrayList<>();
        Map<String, Object> headMap = new HashMap<>();
        //查看自动监测数据
        if ("1".equals(IsAutomaticMonitoringEnt)) {
            vo.setBeginTime(vo.getBeginTime() + " 00:00:00");
            vo.setEndTime(vo.getEndTime() + " 23:00:00");

            automaticList = pollutionAnalyseMapper.getAutomaticMonitorList(vo);
        }
        //查看自行监测数据
        if ("1".equals(IsSuperviseMonitoringEnt)) {
            vo.setBeginTime(vo.getBeginTime() + " 00:00:00");
            vo.setEndTime(vo.getEndTime() + " 23:00:00");
            superviseList = pollutionAnalyseMapper.getSuperviseMonitorList(vo);
        }
        for (Map<String, Object> map : automaticList) {
            strList.add(map.get("samplingTime").toString());
            pollutantList.add(map.get("pollutantCode").toString());
        }
        for (Map<String, Object> map : superviseList) {
            strList.add(map.get("samplingTime").toString());
            pollutantList.add(map.get("pollutantCode").toString());
        }
        //手工和自动监测没有数据，直接返回空值
        if (strList.isEmpty()) {
            return resMap;
        }
        vo.setMonitorList(strList.stream().collect(Collectors.toList()));
        monitorList = pollutionAnalyseMapper.getMonitorAnalyseList(vo);
        for (Map<String, Object> map : monitorList) {
            pollutantList.add(map.get("pollutantCode").toString());
        }

        List<String> isautoList = new ArrayList<>();
        for (Map<String, Object> map : automaticList) {
            if (null == map.get("unit") || "".equals(map.get("unit"))) {
                headMap.put(map.get("pollutantCode").toString(), map.get("PollutantName"));
            } else {
                headMap.put(map.get("pollutantCode").toString(), map.get("PollutantName") + "(" + map.get("unit") + ")");
            }
            if (isautoList.contains(map.get("outportCode").toString() + map.get("samplingTime").toString())) {
                continue;
            }
            isautoList.add(map.get("outportCode").toString() + map.get("samplingTime").toString());
            Map<String, Object> addmap = new HashMap<>();
            addmap.put("monitorTypeCode", "自行监测");
            addmap.put("outPortName", map.get("outPortName") == null ? "" : map.get("outPortName").toString());
            addmap.put("outportCode", map.get("outportCode") == null ? "" : map.get("outportCode").toString());
            addmap.put("samplingTime", map.get("samplingTime") == null ? "" : map.get("samplingTime").toString());
            strList.add(map.get("samplingTime").toString());
            for (String poll : pollutantList) {
                addmap.put(poll, "");
            }
            addmap.put(map.get("pollutantCode").toString(), map.get("measuredConcentration") == null ? "" : map.get("measuredConcentration").toString());
            for (Map<String, Object> automap : automaticList) {
                if (addmap.get("outportCode").equals(automap.get("outportCode")) && addmap.get("samplingTime").equals(automap.get("samplingTime"))) {
                    addmap.put(automap.get("pollutantCode").toString(), automap.get("measuredConcentration") == null ? "" : automap.get("measuredConcentration").toString());
                }
            }
            dateList.add(addmap);
        }
        List<String> issuperviseList = new ArrayList<>();
        for (Map<String, Object> map : superviseList) {
            if (null == map.get("unit") || "".equals(map.get("unit"))) {
                headMap.put(map.get("pollutantCode").toString(), map.get("pollutantName"));
            } else {
                headMap.put(map.get("pollutantCode").toString(), map.get("pollutantName") + "(" + map.get("unit") + ")");
            }
            if (issuperviseList.contains(map.get("outportCode").toString() + map.get("samplingTime").toString())) {
                continue;
            }
            issuperviseList.add(map.get("outportCode").toString() + map.get("samplingTime").toString());
            Map<String, Object> addmap = new HashMap<>();
            addmap.put("monitorTypeCode", "监督性监测");
            addmap.put("outPortName", map.get("outPortName") == null ? "" : map.get("outPortName").toString());
            addmap.put("samplingTime", map.get("samplingTime") == null ? "" : map.get("samplingTime").toString());
            addmap.put(map.get("pollutantCode").toString(), map.get("measuredConcentration") == null ? "" : map.get("measuredConcentration").toString());
            strList.add(map.get("samplingTime").toString());
            for (String poll : pollutantList) {
                addmap.put(poll, "");
            }
            for (Map<String, Object> automap : superviseList) {
                if (map.get("outportCode").equals(automap.get("outportCode")) && map.get("samplingTime").equals(automap.get("samplingTime"))) {
                    addmap.put(automap.get("pollutantCode").toString(), automap.get("measuredConcentration") == null ? "" : automap.get("measuredConcentration").toString());
                }
            }
            dateList.add(addmap);
        }
        //
        List<String> ismonitorList = new ArrayList<>();
        for (Map<String, Object> map : monitorList) {
            if (null == map.get("unit") || "".equals(map.get("unit"))) {
                headMap.put(map.get("pollutantCode").toString(), map.get("pollutantName"));
            } else {
                headMap.put(map.get("pollutantCode").toString(), map.get("pollutantName") + "(" + map.get("unit") + ")");
            }
            if (ismonitorList.contains(map.get("outportCode").toString() + map.get("releaseDate").toString())) {
                continue;
            }
            ismonitorList.add(map.get("outportCode").toString() + map.get("releaseDate").toString());
            Map<String, Object> addmap = new HashMap<>();
            addmap.put("monitorTypeCode", "在线监测");
            addmap.put("outPortName", map.get("outPortName") == null ? "" : map.get("outPortName").toString());
            addmap.put("samplingTime", map.get("releaseDate") == null ? "" : map.get("releaseDate").toString());
            addmap.put(map.get("pollutantCode").toString(), map.get("measuredConcentration") == null ? "" : map.get("measuredConcentration").toString());
            strList.add(map.get("releaseDate").toString());
            for (String poll : pollutantList) {
                addmap.put(poll, "");
            }
            for (Map<String, Object> automap : monitorList) {
                if (map.get("outportCode").equals(automap.get("outportCode")) && map.get("releaseDate").equals(automap.get("releaseDate"))) {
                    addmap.put(automap.get("pollutantCode").toString(), automap.get("measuredConcentration") == null ? "" : automap.get("measuredConcentration").toString());
                }
            }
            dateList.add(addmap);
        }
        resMap.put("resdata", dateList);
        resMap.put("headdata", headMap);
        return resMap;
    }

    @Override
    public Map<String, Object> dataAnalysisChart(PollutionAnalyseVo vo) {
        Map<String, Object> param = new HashMap<>();//查询参数
        Map<String, Object> resMap = new HashMap<>();//查询参数

        List<Map<String, Object>> automaticList = new ArrayList<>();
        List<Map<String, Object>> superviseList = new ArrayList<>();
        Map<String, Object> monitorStatus = pollutionAnalyseMapper.getDataSourceMonitorStatus(vo.getId());
        if (MapUtils.isEmpty(monitorStatus)) {
            return resMap;
        }
        String IsAutomaticMonitoringEnt = monitorStatus.get("IsAutomaticMonitoringEnt").toString();
        String IsSuperviseMonitoringEnt = monitorStatus.get("IsSuperviseMonitoringEnt").toString();
        if ("1".equals(IsAutomaticMonitoringEnt)) {
            vo.setBeginTime(vo.getBeginTime() + " 00:00:00");
            vo.setEndTime(vo.getEndTime() + " 23:00:00");
            automaticList = pollutionAnalyseMapper.getAutomaticMonitorList(vo);
        }
        if ("1".equals(IsSuperviseMonitoringEnt)) {
            vo.setBeginTime(vo.getBeginTime() + " 00:00:00");
            vo.setEndTime(vo.getEndTime() + " 23:00:00");
            superviseList = pollutionAnalyseMapper.getSuperviseMonitorList(vo);
        }
        vo.setBeginTime(vo.getBeginTime() + " 00:00:00");
        vo.setEndTime(vo.getEndTime() + " 23:00:00");
        List<String> monitorList = pollutionAnalyseMapper.findMonitorTimeByid(param);
        List<Object> portList = new ArrayList<>();
        Map<String, Object> dataMap = new HashMap<>();
        if (!automaticList.isEmpty()) {
            for (Map map : automaticList) {
                if (portList.contains(map.get("outportCode") + "-1")) {
                    Map dataMap1 = (Map) dataMap.get(("outportCode") + "-1");
                    List<Object> dataval = (List<Object>) dataMap1.get("dataval");
                    int releaseDate = monitorList.indexOf(map.get("samplingTime").toString());
                    if (-1 == releaseDate) {
                        continue;
                    }
                    dataval.set(releaseDate, map.get("measuredConcentration"));
                }
                Map<String, Object> portMap = new HashMap<>();
                List<Object> datalist = new ArrayList<>();
                for (String monitorTime : monitorList) {
                    datalist.add("-");
                }
                int releaseDate = monitorList.indexOf(map.get("samplingTime").toString());
                if (-1 == releaseDate) {
                    continue;
                }
                datalist.set(releaseDate, map.get("measuredConcentration"));
                portMap.put("portName", map.get("outPortName") == null ? "" : map.get("outPortName").toString());
                portMap.put("dataType", "自行监测");
                portMap.put("dataval", datalist);
                dataMap.put(map.get("outportCode") + "-1", portMap);
            }
        }
        if (!superviseList.isEmpty()) {
            for (Map map : superviseList) {
                if (portList.contains(map.get("outportCode") + "-2")) {
                    Map dataMap1 = (Map) dataMap.get(("outportCode") + "-2");
                    List<Object> dataval = (List<Object>) dataMap1.get("dataval");
                    int releaseDate = monitorList.indexOf(map.get("samplingTime").toString());
                    if (-1 == releaseDate) {
                        continue;
                    }
                    dataval.set(releaseDate, map.get("measuredConcentration"));
                }
                Map<String, Object> portMap = new HashMap<>();
                List<Object> datalist = new ArrayList<>();
                for (String monitorTime : monitorList) {
                    datalist.add("-");
                }
                int releaseDate = monitorList.indexOf(map.get("samplingTime").toString());
                if (-1 == releaseDate) {
                    continue;
                }
                datalist.set(releaseDate, map.get("measuredConcentration"));
                portMap.put("portName", map.get("outPortName") == null ? "" : map.get("outPortName").toString());
                portMap.put("dataType", "监督性监测");
                portMap.put("dataval", datalist);
                dataMap.put(map.get("outportCode") + "-2", portMap);
            }
        }
        vo.setMonitorList(monitorList.stream().collect(Collectors.toList()));
        List<Map<String, Object>> onlineList = pollutionAnalyseMapper.getMonitorAnalyseList(vo);
        if (!onlineList.isEmpty()) {
            for (Map map : onlineList) {
                if (portList.contains(map.get("outportCode") + "-3")) {
                    Map dataMap1 = (Map) dataMap.get(("outportCode") + "-3");
                    List<Object> dataval = (List<Object>) dataMap1.get("dataval");
                    int releaseDate = monitorList.indexOf(map.get("releaseDate").toString());
                    if (-1 == releaseDate) {
                        continue;
                    }
                    dataval.set(releaseDate, map.get("measuredConcentration"));
                }
                Map<String, Object> portMap = new HashMap<>();
                List<Object> datalist = new ArrayList<>();
                for (String monitorTime : monitorList) {
                    datalist.add("-");
                }
                int releaseDate = monitorList.indexOf(map.get("releaseDate").toString());
                if (-1 == releaseDate) {
                    continue;
                }
                datalist.set(releaseDate, map.get("measuredConcentration"));
                portMap.put("portName", map.get("outPortName") == null ? "" : map.get("outPortName").toString());
                portMap.put("dataType", "在线监测");
                portMap.put("dataval", datalist);
                dataMap.put(map.get("outportCode") + "-3", portMap);
            }
        }
        List<Map<String, Object>> resList = new ArrayList<>();
        for (String key : dataMap.keySet()) {
            resList.add((Map<String, Object>) dataMap.get(key));
        }
        resMap.put("ydata", monitorList);
        resMap.put("vadata", resList);
        return resMap;
    }

    @Override
    public List<Map<String, Object>> enterpriseRelation(PollutionAnalyseVo vo) {
        List<Map<String, Object>> jzemissionCount = new ArrayList<>();
        //如果没传时间，增加默认时间，半年
        if (StringUtils.isEmpty(vo.getBeginTime()) && StringUtils.isEmpty(vo.getEndTime())) {
            // 创建一个日期格式化器，用于将LocalDate对象转换为字符串
            vo.setEndTime(DateUtils.dateFormat(new Date(), "yyyy-MM-dd"));
            // 计算半年前的日期
            vo.setBeginTime(DateUtils.dateFormat(DateUtils.addMonths(new Date(), -6), "yyyy-MM-dd"));
        }
        if(StringUtils.isNotEmpty(vo.getOutPortCode())){
            vo.setOutPortCodeList(Arrays.asList(vo.getOutPortCode().split(",")));
        }

        List<Map<String, Object>> emissionCount = pollutionAnalyseMapper.getEmissionCountByPolluteBypagefx(vo);

        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> emissionCount1 = pollutionAnalyseMapper.getEmissionCountByPollutefx(vo);
        Map<String, Map<String, Object>> pollutemap = new HashMap<>();
        for (Map<String, Object> map : emissionCount) {
            Map<String, Object> czmap = pollutemap.get(map.get("ID").toString());
            if (MapUtils.isEmpty(czmap)) {
                czmap = new HashMap<>();
                czmap.put("PolluteName", map.get("PolluteName"));
                czmap.put("ID", map.get("ID"));
            }
            double amount = 0;
            String formattedNumber = String.format("%.3f", amount);
            amount = Double.parseDouble(formattedNumber);
            for (Map<String, Object> emap : emissionCount1) {
                if (map.get("ID").equals(emap.get("ID"))) {
                    czmap.put(emap.get("pollutantCode").toString() + "value", emap.get("totleCouFlow"));
                    amount += Double.parseDouble(emap.get("totleCouFlow").toString());
                }
            }
            String formattedNumber1 = String.format("%.3f", amount);
            amount = Double.parseDouble(formattedNumber1);
            czmap.put("amountValue", amount);
            pollutemap.put(map.get("ID").toString(), czmap);
        }
        Set<String> strings = pollutemap.keySet();
        for (String str : strings) {
            Map<String, Object> map = pollutemap.get(str);
            double jzamount = 0;
            for (Map<String, Object> jzmap : jzemissionCount) {
                if (map.get("ID").equals(jzmap.get("ID"))) {
                    map.put(jzmap.get("pollutantCode").toString() + "jzq", jzmap.get("totleCouFlow"));
                    jzamount += Double.parseDouble(jzmap.get("totleCouFlow").toString());
                }
            }
            String formattedNumber = String.format("%.3f", jzamount);
            jzamount = Double.parseDouble(formattedNumber);
            map.put("amountjz", jzamount);
            list.add(map);
        }
        emissionCount.clear();
        emissionCount.addAll(list);
        return emissionCount;
    }

    @Override
    public List<Map<String, Object>> getPolluteTree(PollutionAnalyseVo vo) {
        List<Map<String, Object>> resultList = pollutionAnalyseMapper.getPolluteTree(vo);

        List<Map<String, Object>> treeList = new ArrayList<>();
        resultList.forEach(map -> {
            Map<String, Object> outputMap = new HashMap<>();
            outputMap.put("name", map.get("outPortName"));
            outputMap.put("id", map.get("outPortCode"));
            if (map.get("CountyCode") != null) {
                boolean countyFlag = false;
                for (Map<String, Object> treeMap : treeList) {
                    if (map.get("CountyCode").equals(treeMap.get("id"))) {
                        List<Map<String, Object>> polluteList = (List<Map<String, Object>>) treeMap.get("children");
                        boolean polluteFlag = false;
                        for (Map<String, Object> polluteMap : polluteList) {
                            if (map.get("polluteId").equals(polluteMap.get("id"))) {
                                List<Map<String, Object>> outportList = (List<Map<String, Object>>) polluteMap.get("children");
                                outportList.add(outputMap);
                                polluteMap.put("children", outportList);
                                polluteFlag = true;
                            }
                        }
                        if (!polluteFlag) {
                            Map<String, Object> polluteMap = new HashMap<>();
                            polluteMap.put("name", map.get("polluteName"));
                            polluteMap.put("id", map.get("polluteId"));
                            List<Map<String, Object>> outportList = new ArrayList<>();
                            outportList.add(outputMap);
                            polluteMap.put("children", outportList);
                            polluteList.add(polluteMap);
                        }
                        countyFlag = true;
                    }
                }
                if (!countyFlag) {
                    Map<String, Object> polluteMap = new HashMap<>();
                    polluteMap.put("name", map.get("polluteName"));
                    polluteMap.put("id", map.get("polluteId"));
                    List<Map<String, Object>> outportList = new ArrayList<>();
                    outportList.add(outputMap);
                    polluteMap.put("children", outportList);
                    List<Map<String, Object>> polluteList = new ArrayList<>();
                    polluteList.add(polluteMap);
                    Map<String, Object> parentMap = new HashMap<>();
                    parentMap.put("name", map.get("County"));
                    parentMap.put("id", map.get("CountyCode"));
                    parentMap.put("children", polluteList);
                    treeList.add(parentMap);
                }
            }
        });
        return treeList;
    }

    @Override
    public List<Map<String, Object>> statisticMonitorFactor(PollutionAnalyseVo vo) {
        List<Map<String, Object>> retList = new ArrayList<>();
        Map<String, Object> retMap1 = new HashMap<>();
        retMap1.put("PolluteName", "氨氮");
        retMap1.put("pollutantCode", "060");
        retList.add(retMap1);

        Map<String, Object> retMap2 = new HashMap<>();
        retMap2.put("PolluteName", "总氮");
        retMap2.put("pollutantCode", "065");
        retList.add(retMap2);

        Map<String, Object> retMap3 = new HashMap<>();
        retMap3.put("PolluteName", "化学需氧量");
        retMap3.put("pollutantCode", "011");
        retList.add(retMap3);

        Map<String, Object> retMap4 = new HashMap<>();
        retMap4.put("PolluteName", "总磷");
        retMap4.put("pollutantCode", "101");
        retList.add(retMap4);

        return retList;
    }

    @Override
    public List<Map<String, Object>> statisticMonitorRate(PollutionAnalyseVo vo) {

        List<Map<String, Object>> dataList = pollutionAnalyseMapper.statisticMonitorRate(vo);
        dataList.forEach(map -> {
            int standardsCount = Integer.parseInt(map.get("monitorCount").toString()) - Integer.parseInt(map.get("warnCount").toString());
            map.put("standardsCount", standardsCount);
            String rate = calculatePercentage(Long.parseLong(Integer.toString(standardsCount)), Long.parseLong(map.get("monitorCount").toString()));
            map.put("rate", rate);
        });
        return dataList;
    }

    @Override
    public List<Map<String, Object>> enterpriseAnalyse(PollutionAnalyseVo vo) {

       vo.setBeginTime(vo.getDateTime()+" 00:00:00");
       vo.setEndTime(vo.getDateTime()+" 23:59:59");

        List<Map<String, Object>> list = new ArrayList<>();

        //查询污染源行政区划
        List<String> pollutionCountyList = pollutionAnalyseMapper.getPollutionCountyCode();
        List<Map<String, Object>>   emissionCountList = pollutionAnalyseMapper.getEmissionCountByCounty(vo);

        for (String county : pollutionCountyList){
            Map<String, Object> czmap = new HashMap<>();
            czmap.put("county",county);
            double amount =0;
            for (Map<String, Object> map: emissionCountList){
                if (county.equals(map.get("County"))){
                    czmap.put(map.get("pollutantCode").toString()+"Value",map.get("totleCouFlow"));
                    amount+=Double.parseDouble(map.get("totleCouFlow").toString());
                }
            }
            String formattedNumber = String.format("%.3f", amount);
            amount = Double.parseDouble(formattedNumber);
            czmap.put("amountValue",amount);
            list.add(czmap);
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> polluteTypeAnalyse(PollutionAnalyseVo vo) {
        vo.setBeginTime(vo.getDateTime()+" 00:00:00");
        vo.setEndTime(vo.getDateTime()+" 23:59:59");

        List<Map<String, Object>> list = new ArrayList<>();

        List<String> industryList= pollutionAnalyseMapper.getIndustryDatas();
        List<Map<String, Object>>   emissionCountList = pollutionAnalyseMapper.getEmissionIndustry(vo);
        List<Map<String, Object>> monitorFactorList=statisticMonitorFactor(vo);
        for (String industry : industryList){
            Map<String, Object> czmap = new HashMap<>();
            czmap.put("industry",industry);
            double amount =0;
            boolean flag=false;
            for (Map<String, Object> monitorFactorMap: monitorFactorList){
              String pollutantCode=String.valueOf(monitorFactorMap.get("pollutantCode"));
                for (Map<String, Object> map: emissionCountList){
                    if (industry.equals(map.get("DicName")) && pollutantCode.equals(String.valueOf(map.get("pollutantCode")))){
                        czmap.put(map.get("pollutantCode").toString()+"Value",map.get("totleCouFlow"));
                        amount+=Double.parseDouble(map.get("totleCouFlow").toString());
                        flag=true;
                    }
                }
                if(!flag){
                    czmap.put(monitorFactorMap.get("pollutantCode").toString()+"Value",0);
                }
            }

            String formattedNumber = String.format("%.3f", amount);
            amount = Double.parseDouble(formattedNumber);
            czmap.put("amountValue",amount);
            list.add(czmap);
        }
        return list;
    }

    @Override
    public Map<String, Object> reportAnalyseDay(PollutionAnalyseVo vo) {
        vo.setBeginTime(vo.getBeginTime()+" 00:00:00");
        vo.setEndTime(vo.getEndTime()+" 23:59:59");

        //查询排口信息
        List<Map<String,Object>> outportList = pollutionAnalyseMapper.selectOutPutByCode(vo);
        //查询监测数据
        List<Map<String,Object>> dataList= pollutionAnalyseMapper.statementForHour(vo);
        //查询排口污染物信息
        List<Map<String,Object>> outputList = pollutionAnalyseMapper.selectOutputpollutantList(vo);
        //排序
        outputList.sort(Comparator.comparingInt(map -> Integer.parseInt(map.get("pollutantCode").toString().replaceAll("\\D+", ""))));
        Map<String,Object> totalMap = new LinkedHashMap<>();//表头map
        List<Map<String, Object>> colslist =new ArrayList<>();
        outputList.forEach(outputMap -> {
            String pollutantName = outputMap.get("pollutantName").toString();
            String codeOrder = outputMap.get("codeOrder")==null?"-1":outputMap.get("codeOrder").toString();
            String unit = outputMap.get("unit")==null?"":outputMap.get("unit").toString();
            String flowunit = outputMap.get("flowUnit")==null?"":outputMap.get("flowUnit").toString();
            String total = outputMap.get("pollutantName").toString();
            if(null!= outputMap.get("unit")&&StringUtils.isNotEmpty(outputMap.get("unit").toString())){
                total += "（"+outputMap.get("unit")+"）";
            }
            totalMap.put(outputMap.get("pollutantCode")+"AvgStrength",total);
            if(null!=outputMap.get("isShowFlow")&&outputMap.get("isShowFlow").equals(1)){
                String flowTotal = outputMap.get("pollutantName")+"排放量";
                if(null!=outputMap.get("flowUnit") && StringUtils.isNotEmpty(outputMap.get("flowUnit").toString())){
                    flowTotal += "（"+outputMap.get("flowUnit")+"）";
                }
                totalMap.put(outputMap.get("pollutantCode")+"couFlow",flowTotal);
            }
            Map<String,Object> propMap = new HashMap<>();
            propMap.put("prop",outputMap.get("pollutantCode")+"AvgStrength");
            propMap.put("name",pollutantName);
            propMap.put("unit",unit);
            propMap.put("sort",Integer.parseInt(codeOrder));
            colslist.add(propMap);
        });
        Map<String,Object> sumMap = new LinkedHashMap<>();//合计
        Map<String,Object> avgMap = new LinkedHashMap<>();//平均值
        Map<String,Object> maxMap = new LinkedHashMap<>();//最大值
        Map<String,Object> minMap = new LinkedHashMap<>();//最小值
        dataList.forEach(map -> {
            Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                if (null != totalMap.get(entry.getKey())) {
                    //计算和值
                    if(sumMap==null||sumMap.get(entry.getKey())==null){
                        sumMap.put(entry.getKey(),map.get(entry.getKey()));
                    }else {
                        sumMap.put(entry.getKey(), new BigDecimal(sumMap.getOrDefault(entry.getKey(), 0).toString()).add(new BigDecimal(map.get(entry.getKey()).toString())));
                    }
                    //获取最大值
                    if(maxMap==null||maxMap.get(entry.getKey())==null||new BigDecimal(maxMap.get(entry.getKey()).toString()).compareTo(new BigDecimal(map.get(entry.getKey()).toString()))<0){
                        maxMap.put(entry.getKey(),map.get(entry.getKey()));
                    }
                    //获取最小值
                    if(minMap==null||minMap.get(entry.getKey())==null||new BigDecimal(minMap.get(entry.getKey()).toString()).compareTo(new BigDecimal(map.get(entry.getKey()).toString()))>0){
                        minMap.put(entry.getKey(),map.get(entry.getKey()));
                    }
                }else if(!entry.getKey().equals("monitorTime")){
                    iterator.remove();
                }
            }
        });
        for (String key : sumMap.keySet()){
            if(null!=sumMap.get(key)){
                avgMap.put(key,new BigDecimal(sumMap.get(key).toString()).divide(new BigDecimal(dataList.size()),BigDecimal.ROUND_CEILING));//计算平均值
            }else{
                avgMap.put(key,null);
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("columnTitle",totalMap);
        resultMap.put("dataList",dataList);
        resultMap.put("sum",sumMap);
        resultMap.put("avg",avgMap);
        resultMap.put("max",maxMap);
        resultMap.put("min",minMap);
        resultMap.put("beginTime",vo.getBeginTime());
        resultMap.put("endTime",vo.getEndTime());
        resultMap.put("column",colslist);
        if(!outportList.isEmpty()){
            resultMap.put("outportName",outportList.get(0).get("outPortName"));
            resultMap.put("PolluteName", outportList.get(0).get("PolluteName"));
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> reportAnalyseWeek(PollutionAnalyseVo vo) {
        vo.setBeginTime(vo.getBeginTime()+" 00:00:00");
        vo.setEndTime(vo.getEndTime()+" 23:59:59");
        //查询排口信息
        List<Map<String,Object>> outportList = pollutionAnalyseMapper.selectOutPutByCode(vo);

        List<Map<String,Object>> dataList= pollutionAnalyseMapper.statementForDayLocal(vo);
        //查询排口污染物信息
        List<Map<String,Object>> outputList = pollutionAnalyseMapper.selectOutputpollutantList(vo);
        //排序
        outputList.sort(Comparator.comparingInt(map -> Integer.parseInt(map.get("pollutantCode").toString().replaceAll("\\D+", ""))));
        Map<String,Object> totalMap = new LinkedHashMap<>();//表头map
        List<Map<String, Object>> colslist =new ArrayList<>();
        outputList.forEach(outputMap -> {
            String pollutantName = outputMap.get("pollutantName").toString();
            String codeOrder = outputMap.get("codeOrder")==null?"-1":outputMap.get("codeOrder").toString();
            String unit = outputMap.get("unit")==null?"":outputMap.get("unit").toString();
            String flowunit = outputMap.get("flowUnit")==null?"":outputMap.get("flowUnit").toString();
            String total = outputMap.get("pollutantName").toString();
            if(null!= outputMap.get("unit")&&StringUtils.isNotEmpty(outputMap.get("unit").toString())){
                total += "（"+outputMap.get("unit")+"）";
            }
            totalMap.put(outputMap.get("pollutantCode")+"AvgStrength",total);
            if(null!=outputMap.get("isShowFlow")&&outputMap.get("isShowFlow").equals(1)){
                String flowTotal = outputMap.get("pollutantName")+"排放量";
                if(null!=outputMap.get("flowUnit")){
                    flowTotal += "（"+outputMap.get("flowUnit")+"）";
                }
                totalMap.put(outputMap.get("pollutantCode")+"couFlow",flowTotal);
            }
            Map<String,Object> propMap = new HashMap<>();
            propMap.put("prop",outputMap.get("pollutantCode")+"AvgStrength");
            propMap.put("name",pollutantName);
            propMap.put("unit",unit);
            propMap.put("sort",Integer.parseInt(codeOrder));
            colslist.add(propMap);
        });
        Map<String,Object> sumMap = new LinkedHashMap<>();//合计
        Map<String,Object> avgMap = new LinkedHashMap<>();//平均值
        Map<String,Object> maxMap = new LinkedHashMap<>();//最大值
        Map<String,Object> minMap = new LinkedHashMap<>();//最小值
        dataList.forEach(map -> {
            Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                if (null != totalMap.get(entry.getKey())) {
                    //计算和值
                    if(sumMap==null||sumMap.get(entry.getKey())==null){
                        sumMap.put(entry.getKey(),map.get(entry.getKey()));
                    }else {
                        sumMap.put(entry.getKey(), new BigDecimal(sumMap.getOrDefault(entry.getKey(), 0).toString()).add(new BigDecimal(map.get(entry.getKey()).toString())));
                    }
                    //获取最大值
                    if(maxMap==null||maxMap.get(entry.getKey())==null||new BigDecimal(maxMap.get(entry.getKey()).toString()).compareTo(new BigDecimal(map.get(entry.getKey()).toString()))<0){
                        maxMap.put(entry.getKey(),map.get(entry.getKey()));
                    }
                    //获取最小值
                    if(minMap==null||minMap.get(entry.getKey())==null||new BigDecimal(minMap.get(entry.getKey()).toString()).compareTo(new BigDecimal(map.get(entry.getKey()).toString()))>0){
                        minMap.put(entry.getKey(),map.get(entry.getKey()));
                    }
                }else if(!entry.getKey().equals("monitorTime")){
                    iterator.remove();
                }
            }
        });
        for (String key : sumMap.keySet()){
            if(null!=sumMap.get(key)){
                avgMap.put(key,new BigDecimal(sumMap.get(key).toString()).divide(new BigDecimal(dataList.size()),BigDecimal.ROUND_CEILING));//计算平均值
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("columns",totalMap);
        resultMap.put("list",dataList);
        resultMap.put("sum",sumMap);
        resultMap.put("avg",avgMap);
        resultMap.put("max",maxMap);
        resultMap.put("min",minMap);
        resultMap.put("column",colslist);
        resultMap.put("beginTime",vo.getBeginTime());
        resultMap.put("endTime",vo.getEndTime());
        if(!outportList.isEmpty()){
            resultMap.put("outportName",outportList.get(0).get("outPortName"));
            resultMap.put("PolluteName", outportList.get(0).get("PolluteName"));
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> reportAnalyseMonth(PollutionAnalyseVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> reportAnalyseQuarter(PollutionAnalyseVo vo) {
        vo.setBeginTime(vo.getBeginTime()+" 00:00:00");
        vo.setEndTime(vo.getEndTime()+" 23:59:59");
        //查询排口信息
        List<Map<String,Object>> outportList = pollutionAnalyseMapper.selectOutPutByCode(vo);
        //查询监测数据
        List<Map<String,Object>> dataList= pollutionAnalyseMapper.statementForMonthLocal(vo);
        //查询排口污染物信息
        List<Map<String,Object>> outputList = pollutionAnalyseMapper.selectOutputpollutantList(vo);
        //排序
        outputList.sort(Comparator.comparingInt(map -> Integer.parseInt(map.get("pollutantCode").toString().replaceAll("\\D+", ""))));
        Map<String,Object> totalMap = new LinkedHashMap<>();//表头map
        List<Map<String, Object>> colslist =new ArrayList<>();
        outputList.forEach(outputMap -> {
            String pollutantName = outputMap.get("pollutantName").toString();
            String codeOrder = outputMap.get("codeOrder")==null?"-1":outputMap.get("codeOrder").toString();
            String unit = outputMap.get("unit")==null?"":outputMap.get("unit").toString();
            String flowunit = outputMap.get("flowUnit")==null?"":outputMap.get("flowUnit").toString();
            String total = outputMap.get("pollutantName").toString();
            if(null!= outputMap.get("unit")&&StringUtils.isNotEmpty(outputMap.get("unit").toString())){
                total += "（"+outputMap.get("unit")+"）";
            }
            totalMap.put(outputMap.get("pollutantCode")+"AvgStrength",total);
            if(null!=outputMap.get("isShowFlow")&&outputMap.get("isShowFlow").equals(1)){
                String flowTotal = outputMap.get("pollutantName")+"排放量";
                if(null!=outputMap.get("flowUnit")){
                    flowTotal += "（"+outputMap.get("flowUnit")+"）";
                }
                totalMap.put(outputMap.get("pollutantCode")+"couFlow",flowTotal);
            }
            Map<String,Object> propMap = new HashMap<>();
            propMap.put("prop",outputMap.get("pollutantCode")+"AvgStrength");
            propMap.put("name",pollutantName);
            propMap.put("unit",unit);
            propMap.put("sort",Integer.parseInt(codeOrder));
            colslist.add(propMap);
        });
        Map<String,Object> sumMap = new LinkedHashMap<>();//合计
        Map<String,Object> avgMap = new LinkedHashMap<>();//平均值
        Map<String,Object> maxMap = new LinkedHashMap<>();//最大值
        Map<String,Object> minMap = new LinkedHashMap<>();//最小值
        dataList.forEach(map -> {
            Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                if (null != totalMap.get(entry.getKey())) {
                    //计算和值
                    if(sumMap==null||sumMap.get(entry.getKey())==null){
                        sumMap.put(entry.getKey(),map.get(entry.getKey()));
                    }else {
                        sumMap.put(entry.getKey(), new BigDecimal(sumMap.getOrDefault(entry.getKey(), 0).toString()).add(new BigDecimal(map.get(entry.getKey()).toString())));
                    }
                    //获取最大值
                    if(maxMap==null||maxMap.get(entry.getKey())==null||new BigDecimal(maxMap.get(entry.getKey()).toString()).compareTo(new BigDecimal(map.get(entry.getKey()).toString()))<0){
                        maxMap.put(entry.getKey(),map.get(entry.getKey()));
                    }
                    //获取最小值
                    if(minMap==null||minMap.get(entry.getKey())==null||new BigDecimal(minMap.get(entry.getKey()).toString()).compareTo(new BigDecimal(map.get(entry.getKey()).toString()))>0){
                        minMap.put(entry.getKey(),map.get(entry.getKey()));
                    }
                }else if(!entry.getKey().equals("monitorTime")){
                    iterator.remove();
                }
            }
        });
        for (String key : sumMap.keySet()){
            if(null!=sumMap.get(key)){
                avgMap.put(key,new BigDecimal(sumMap.get(key).toString()).divide(new BigDecimal(dataList.size()),BigDecimal.ROUND_CEILING));//计算平均值
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("columns",totalMap);
        resultMap.put("list",dataList);
        resultMap.put("sum",sumMap);
        resultMap.put("avg",avgMap);
        resultMap.put("max",maxMap);
        resultMap.put("min",minMap);
        resultMap.put("column",colslist);
        resultMap.put("beginTime",vo.getBeginTime());
        resultMap.put("endTime",vo.getEndTime());
        if(!outportList.isEmpty()){
            resultMap.put("outportName",outportList.get(0).get("outPortName"));
            resultMap.put("PolluteName", outportList.get(0).get("PolluteName"));
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> reportAnalyseSemiannual(PollutionAnalyseVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> reportAnalyseYear(PollutionAnalyseVo vo) {
        return null;
    }


    private static String calculatePercentage(long numerator, long denominator) {
        if (denominator == 0) {
            throw new IllegalArgumentException("Denominator cannot be zero.");
        }

        BigDecimal percentage = new BigDecimal(numerator)
                .divide(new BigDecimal(denominator), 2, BigDecimal.ROUND_HALF_UP)
                .multiply(new BigDecimal(100));

        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(percentage) + "%";
    }
}
